<template>
  <div class="cluster-layer_container">
    cluster-layer
  </div>
</template>
<script>
export default {
  data() {
    return {
      map: null,
      clusterData: {},
    }
  },
  methods: {
    init(options) {
      this.map = options.map;
      this.getClusterData()
        .then((res) => {
          console.log("clusterData========>", res);
          this.clusterData = {
            type: res.type,
            features: res.features,
          };
          console.log(this.clusterData);
          
          this.addClusterLayer(this.clusterData);
        })
        .catch((err) => {
          console.log("获取clusterData失败=======>", err);
        });
    },
    getClusterData() {
      return new Promise((resolve, reject) => {
        const url = "https://docs.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson";
        fetch(url)
          .then(response => response.json())
          .then(data => {
            resolve(data);
          })
          .catch(error => {
            console.error("获取cluster的数据失败 ===>>>::", error);
          });
      })
    },
    addClusterLayer(data) {
      this.map.addSource("clusterSourceId", {
        type: "geojson",
        data,
        cluster: true,
        clusterMaxZoom: 10, // Max zoom to cluster points on
        clusterRadius: 50 // Radius of each cluster when clustering points (defaults to 50)
      });

      

      // 添加聚合图层
      this.map.addLayer({
        id: 'clusters',
        type: 'circle',
        source: 'clusterSourceId',
        filter: ['has', 'point_count'],
        paint: {
          'circle-color': [ 'step', ['get', 'point_count'], '#51bbd6', 100, '#f1f075', 750, '#f28cb1' ],
          'circle-radius': [ 'step', ['get', 'point_count'], 20, 100, 30, 750, 40 ]
        }
      });
      
      // 添加count图层
      this.map.addLayer({
        id: 'cluster-count',
        type: 'symbol',
        source: 'clusterSourceId',
        filter: ['has', 'point_count'],
        layout: {
          'text-field': ['get', 'point_count_abbreviated'],
          'text-font': ['DIN Offc Pro Medium', 'Arial Unicode MS Bold'],
          'text-size': 12
        },
      });

      // 添加非聚合图层
      this.addUnclusteredLayer();

      
     
      this.map.on('click', 'clusters', (e) => {
        this.clustersLayerClickEvent(e);
      });
    },
    addUnclusteredLayer() {
      this.loadImage().then((res) => {
        console.log('res', res);
        // this.map.addLayer({
        //   id: 'unclustered-point',
        //   type: 'circle',
        //   source: 'clusterSourceId',
        //   filter: ['!', ['has', 'point_count']],
        //   paint: {
        //     'circle-color': '#11b4da',
        //     'circle-radius': 4,
        //     'circle-stroke-width': 1,
        //     'circle-stroke-color': '#fff'
        //   }
        // });
          
        this.map.addLayer({
          id: 'unclustered-point',
          type: 'symbol',
          source: 'clusterSourceId',
          filter: ['!', ['has', 'point_count']],
          layout: {
            'icon-image': 'device', // reference the image
            'icon-size': 0.25
          },
        });
      });
    },

    clustersLayerClickEvent(e) {
      let self = this;
      var features = this.map.queryRenderedFeatures(e.point, {
          layers: ['clusters']
        });
      var clusterId = features[0].properties.cluster_id;
      this.map.getSource('clusterSourceId').getClusterExpansionZoom(
        clusterId,
        function(err, zoom) {
          if (err) return;
          self.map.easeTo({
            center: features[0].geometry.coordinates,
            zoom: zoom
          });
        }
      );
    },
    loadImage() {
      return new Promise((resolve, reject) => {
        let imgUrl = require("../../../assets/images/device_default.png")
        this.map.loadImage(
          imgUrl,
          (error, image) => {
            if (error) throw error;
            this.map.addImage('device', image);
            resolve(image);
          }
        );
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.cluster-layer {
  &_container {
    position: absolute;
    top: 50px;
    right: 20px;
    width: 300px;
    min-height: 200px;
    background-color: #fff;
  }
}
</style>